package com.atwisdom.star.core.bsl.business.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.common.vo.StatusCode;
import com.atwisdom.star.core.bsl.business.DataChangeBslService;
import com.atwisdom.star.core.bsl.business.entity.ApiConfigInfo;
import com.atwisdom.star.core.bsl.business.entity.ConfigInfo;
import com.atwisdom.star.core.bsl.business.entity.RefInfo;
import com.atwisdom.star.core.bsl.business.entity.RefProp;
import com.atwisdom.star.core.bsl.business.utils.ConstantInfo;
import com.atwisdom.star.core.bsl.business.utils.RestTemplateUtil;
import com.atwisdom.star.core.dao.pojo.functionClass.ApiConfig;
import com.atwisdom.star.core.dao.pojo.functionClass.ApiSendData;
import com.atwisdom.star.core.dao.pojo.modelClass.consume.ConsumeInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.resource.ResourceInstance;
import com.atwisdom.star.core.dsl.functionClass.Impl.ApiConfigDslServiceImpl;
import com.atwisdom.star.core.dsl.functionClass.Impl.ApiSendDataDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.consume.Impl.ConsumeInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.hier.HierInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.logic.Impl.LogicInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.resource.Impl.ResourceInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.tank.Impl.TankInstanceDslServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class DataChangeBslServiceImpl implements DataChangeBslService {
    @Autowired
    private ApiConfigDslServiceImpl apiConfigDslService;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private ConsumeInstanceDslServiceImpl consumeInstanceDslService;
    @Autowired
    private ResourceInstanceDslServiceImpl resourceInstanceDslService;
    @Autowired
    private LogicInstanceDslServiceImpl logicInstanceDslService;
    @Autowired
    private TankInstanceDslServiceImpl tankInstanceDslService;
    @Autowired
    private HierInstanceDslService hierInstanceDslService;
    @Autowired
    private ApiSendDataDslServiceImpl apiSendDataDslService;
    private List<ApiConfigInfo> apiConfigInfoList = new ArrayList<>();

    public DataChangeBslServiceImpl(ApiConfigDslServiceImpl apiConfigDslService) {
        this.apiConfigDslService = apiConfigDslService;
        this.initApiConfigInfoList();
    }

    /**
     * 初始化接口配置信息
     */
    private void initApiConfigInfoList() {
        List<ApiConfig> apiConfigs = apiConfigDslService.queryByEnable();
        for (ApiConfig apiConfig : apiConfigs) {
            JSONArray config = apiConfig.getConfig();
            List<ConfigInfo> configInfoList = new ArrayList<>();
            this.buildConfig(config, configInfoList);
            ApiConfigInfo apiConfigInfo = new ApiConfigInfo(apiConfig.getId(),
                    apiConfig.getSysName(),
                    apiConfig.getServiceName(),
                    apiConfig.getOpType(),
                    apiConfig.getModel(),
                    apiConfig.getClassName(),
                    apiConfig.getFieldNames(),
                    apiConfig.getEnable(),
                    configInfoList);
            apiConfigInfoList.add(apiConfigInfo);
        }
    }

    private void buildConfig(JSONArray config, List<ConfigInfo> configInfoList) {
        for (Object o : config) {
            JSONObject tempObj = (JSONObject)o;
            ConfigInfo configInfo = JSONObject.parseObject(JSON.toJSONString(o), ConfigInfo.class);
            JSONArray modelArr = tempObj.getJSONArray("modelArr");
            if(modelArr!=null && modelArr.size() >2){
                String model = (String)modelArr.get(0);
                String className = (String)modelArr.get(2);
                configInfo.setModel(model);
                configInfo.setClassName(className);
            }
            JSONObject addition = new JSONObject();
            JSONArray additionList = tempObj.getJSONArray("additionList");
            if(CollectionUtil.isNotEmpty(additionList)){
                if(addition == null){
                    addition = new JSONObject();
                }
                for (Object obj : additionList) {
                   JSONObject jsonObj = (JSONObject)obj;
                    String key = jsonObj.getString("key");
                    String value = jsonObj.getString("value");
                    if(StringUtils.isNotBlank(key)){
                        addition.put(key,value);
                    }
                }
                configInfo.setAddition(addition);
            }
            JSONObject jsonObject = tempObj.getJSONObject("ref");
            JSONArray jsonArray = jsonObject.getJSONArray("modelArr");
            if(jsonArray!=null && jsonArray.size() >2){
                String refModel = (String)modelArr.get(0);
                String refClassName = (String)modelArr.get(2);
                RefInfo refInfo = configInfo.getRef();
                refInfo.setModel(refModel);
                refInfo.setClassName(refClassName);
            }
            configInfoList.add(configInfo);
        }
    }

    @Override
    public boolean needTrans(String className, String model, String opType) {
        ApiConfigInfo apiConfigInfo = apiConfigInfoList.stream()
                .filter(conf ->conf.getClassName()!=null
                        && conf.getClassName().equalsIgnoreCase(className)
                        && conf.getModel()!=null
                        && conf.getModel().equalsIgnoreCase(model)
                        && conf.getOpType()!=null
                        && conf.getOpType().equalsIgnoreCase(opType)).findFirst().orElse(null);
        if (apiConfigInfo != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ApiConfigInfo getApiConfigInfo(String className, String model, String opType) {
        ApiConfigInfo apiConfigInfo = apiConfigInfoList.stream().filter(conf -> conf.getClassName().equalsIgnoreCase(className) && conf.getModel().equalsIgnoreCase(model) && conf.getOpType().equalsIgnoreCase(opType)).findFirst().orElse(null);
        return apiConfigInfo;
    }

    public ResultInfo<?> sendDataTest() {
        this.initSendData();
//        ApiSendData apiSendData = apiSendDataDslService.queryById(7l);
//        JSONObject jsonObject = this.sendData(apiSendData.getClassName(), apiSendData.getModel(), apiSendData.getOpType(), apiSendData.getFieldValues());
//        return JsonResult.success(jsonObject);
        return null;
    }

    @Scheduled(cron = "#{erpCronExpression.generateErpCron()}")
    public ResultInfo<?> transferData() {
        System.out.println(new Date());
        List<ApiSendData> apiSendDataList = apiSendDataDslService.queryByStatus(0);
        for (ApiSendData apiSendData : apiSendDataList) {
            try {
                this.sendData(apiSendData);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return JsonResult.success(StatusCode.SUCCESS);
    }

    /**
     * 数据发送
     *
     * @param apiSendData 上传数据
     * @return 反回发送成功及失败
     */
    @Override
    public void sendData(ApiSendData apiSendData) {
        String className = apiSendData.getClassName();
        String model = apiSendData.getModel();
        String opType = apiSendData.getOpType();
        ApiConfigInfo apiConfigInfo = getApiConfigInfo(className, model, opType);
        if (apiConfigInfo == null) {
            return;
        }
        String serviceName = apiConfigInfo.getServiceName();
        List<ConfigInfo> configInfos = apiConfigInfo.getConfigInfoList();
        List<ConfigInfo> tempConfigInfoList = new ArrayList<>(configInfos);
        List<JSONObject> sourceDataList = new ArrayList<>();
        this.initSourceDataList(apiSendData,sourceDataList);
        ConfigInfo configInfo = tempConfigInfoList.remove(0);
        List<JSONObject> firstSourceList = getFirstSourceData(configInfo, sourceDataList);
        for (JSONObject jsonObject : firstSourceList) {
            JSONObject sendJsonObject = new JSONObject();
            for (ConfigInfo tempInfo : tempConfigInfoList) {
                ConfigInfo info = new ConfigInfo();
                BeanUtils.copyProperties(tempInfo,info);
                String condition = info.getCondition();
                Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}");
                Matcher matcher = pattern.matcher(condition);
                List<String> matches = new ArrayList<>();
                while (matcher.find()) {
                    matches.add(matcher.group(1));
                }
                for (String match : matches) {
                     String fieldKey =   match.substring(match.indexOf(".")+1);
                     condition = condition.replace("${" + match + "}", jsonObject.getString(fieldKey));
                }
                info.setCondition(condition);
                sourceDataList.add(jsonObject);
                this.buildSendData(info, sourceDataList, sendJsonObject);
                sourceDataList.removeIf(s->s.getLong("firstSourceId") !=null && s.getLong("firstSourceId") == jsonObject.getLong("firstSourceId"));
            }
           this.restSendData(apiSendData, serviceName, sendJsonObject);
        }
    }

    private List<JSONObject> getFirstSourceData(ConfigInfo configInfo, List<JSONObject> sourceDataList) {
        String condition = buildRefCondition(configInfo, sourceDataList, configInfo.getCondition());
        boolean hierFlag = configInfo.isHierFlag();
        String model = configInfo.getModel();
        String className = configInfo.getClassName();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        if (hierFlag) {
            List<HierInstance> hinsList = this.hierInstanceDslService.query(model, className, condition);
            for (HierInstance ins : hinsList) {
                JSONObject values = ins.getValues();
                values.put("id", ins.getId());
                values.put("hierFlag", true);
                values.put("createTime", ins.getCreateTime());
                values.put("firstSourceId", ins.getId());
                values.put("model",model);
                values.put("className",className);
                values.put("firstSourceId", ins.getId());
                jsonObjectList.add(values);
            }
        } else {
            jsonObjectList = fetchInstanceValues(model, className, condition);
        }
        return jsonObjectList;
    }

    private List<JSONObject> fetchInstanceValues(String model, String className, String condition) {
        List<JSONObject> jsonObjectList;
        switch (model) {
            case "logic":
                jsonObjectList = this.logicInstanceDslService.queryWithoutHier(condition, className, null);
                break;
            case "consume":
                jsonObjectList = this.consumeInstanceDslService.query(condition, className, null);
                break;
            case "resource":
                jsonObjectList = this.resourceInstanceDslService.query(condition, className, null);
                break;
            case "tank":
                jsonObjectList = this.tankInstanceDslService.queryWithoutHier(condition, className, null);
                break;
            default:
                jsonObjectList =new ArrayList<>();
                break;
        }

        List<JSONObject> valuesList = new ArrayList<>();
        for (JSONObject jsonObj : jsonObjectList) {
            JSONObject values = jsonObj.getJSONObject("values");
            values.put("id", jsonObj.get("id"));
            values.put("hierFlag", false);
            values.put("createTime", jsonObj.get("createTime"));
            values.put("model",model);
            values.put("className",className);
            values.put("firstSourceId", jsonObj.get("id"));
            valuesList.add(values);
        }
        return valuesList;
    }

    private Boolean restSendData(ApiSendData apiSendData, String serviceName, JSONObject sendJsonObject) {
        Boolean resultFlag;
        try {
            JSONObject result = restTemplateUtil.post(serviceName, sendJsonObject, MediaType.APPLICATION_JSON);
            String resultString = result.getString("status");
            if ("success".equalsIgnoreCase(resultString)) {
                apiSendData.setStatus(4);
            } else {
                apiSendData.setStatus(3);
            }
            apiSendData.setSendData(sendJsonObject);
            resultFlag = this.apiSendDataDslService.update(apiSendData);
        } catch (Exception ex) {
            System.out.println("连接异常：" + ex.getMessage());
            apiSendData.setComments("连接异常"+ex.getMessage());
            apiSendData.setStatus(3);
            apiSendData.setSendData(sendJsonObject);
            resultFlag = this.apiSendDataDslService.update(apiSendData);
        }
        return resultFlag;
    }

    public void initSourceDataList(ApiSendData apiSendData,List<JSONObject> sourceDataList){
        String className = apiSendData.getClassName();
        String model = apiSendData.getModel();
        boolean hierFlag = apiSendData.isHierFlag();
        JSONArray fieldValues = apiSendData.getFieldValues();
        String condition = "";
        for (Object o : fieldValues) {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(o));
            String fieldName = jsonObject.getString(ConstantInfo.FIELD_NAME);
            String fieldType = jsonObject.getString(ConstantInfo.FIELD_TYPE);
            String fieldValue = jsonObject.getString(ConstantInfo.FIELD_VALUE);
            condition = buildCondition(condition, fieldName, fieldType, fieldValue);
        }
        JSONObject values = buildSourceData(hierFlag, model, className, condition,"",0);
        if (values != null) {
            sourceDataList.add(values);
        }
    }

    /**
     * 构建发送数据
     *
     * @param configInfo     配置信息
     * @param sourceDataList 已经获取的数据列表
     * @param sendJsonObject 返回发送数据
     */
    private void buildSendData(ConfigInfo configInfo,List<JSONObject> sourceDataList, JSONObject sendJsonObject) {
        String condition = configInfo.getCondition();
        String className = configInfo.getClassName();
        String sourceName = configInfo.getSourceName();
        int sourceType = configInfo.getSourceType();

        String parentSourceName = configInfo.getParentSourceName();
        int parentSourceType = configInfo.getParentSourceType();

        String model = configInfo.getModel();
        boolean hierFlag = configInfo.isHierFlag();

        JSONObject sendObj = new JSONObject();
        condition = buildRefCondition(configInfo, sourceDataList, condition);
        Map<String, String> mapper = configInfo.getMapper();
        JSONObject addition = configInfo.getAddition();

        JSONObject values = getRefSourceData(configInfo, sourceDataList);
        if (values == null) {
            values = buildSourceData(hierFlag, model, className, condition, sourceName, sourceType);
            if(values!=null && values.size() >0){
                sourceDataList.add(values);
            }
        }
        if (values != null) {
            JSONObject finalSendObj = sendObj;
            JSONObject finalValues = values;
            mapper.forEach((k, v) -> {
                List<String> keyList = Arrays.asList(v.split(","));
                keyList.forEach(sk -> finalSendObj.put(sk, finalValues.get(k)));
            });
        }
        if (addition != null && addition.size() > 0) {
            sendObj.putAll(addition);
        }
        dealSendData(sendJsonObject, sendObj, sourceName, sourceType, parentSourceName, parentSourceType);
    }

    private JSONObject getRefSourceData(ConfigInfo configInfo,List<JSONObject> sourceDataList){
        RefInfo ref = configInfo.getRef();
        boolean hierFlag = configInfo.isHierFlag();
        return sourceDataList.stream().filter(json -> json.getBoolean("hierFlag") == hierFlag && json.getString(ConstantInfo.MODEL).equalsIgnoreCase(ref.getModel()) && json.getString(ConstantInfo.CLASS_NAME).equalsIgnoreCase(ref.getClassName())).findFirst().orElse(null);
    }

    private JSONObject buildSourceData(boolean hierFlag, String model, String className, String condition,String sourceName,int sourceType ) {
        JSONObject values;
        if(hierFlag){
            HierInstance hierInstance = this.hierInstanceDslService.query(model, className, condition).stream().findFirst().orElse(null);
            if (hierInstance == null) {
                return null;
            }
            values = hierInstance.getValues();
            values.put("id", hierInstance.getId());
            values.put("hierFlag", true);
            values.put("createTime", hierInstance.getCreateTime());
        }else{
            values = getInsValues(model, className, condition);
        }
        values.put(ConstantInfo.MODEL, model);
        values.put(ConstantInfo.CLASS_NAME, className);
        values.put(ConstantInfo.SOURCE_NAME, sourceName);
        values.put(ConstantInfo.SOURCE_TYPE, sourceType);
        return values;
    }

    public void initSendData() {
        //1、存货分类（物料分类）
        this.initHierSendInfo("logic", "globalDict", "containerId = 256 and parentId = 'root'");
//        //2、存货档案（物料档案）
//        this.initConsumeSendInfo("material");
//        //3、计量单位
//        this.initConsumeSendInfo("materialUnit");
//        //4、供应商分类
//
//        //5、供应商档案
//        this.initLogicSendInfo("supplier"," 1 = 1");
//        //6、客户档案
//        this.initResourceSendInfo("customer");
//        //7、部门档案
//        this.initHierSendInfo("staticLogic", "dept", " linkId is null or linkId = '' ");
//        //8、人员档案
//        this.initResourceSendInfo("Person");
//        //9、仓库
//        this.initHierSendInfo("twins", "warehouse", "nodeId!='root' and ( linkId is null or linkId = '') ");
          //10、采购入库
//        this.initLogicSendInfo("receiptOrder"," isApproved = true ");
    }

    /**
     * 1、存货分类（物料分类）
     */
    private void initHierSendInfo(String model, String className, String condition) {
        condition += " and id not in (select sendValue from api_send_data where sendValue is not null and model ='" + model + "' and className ='" + className + "')";
        List<HierInstance> hierInsList = this.hierInstanceDslService.query(model, className, condition);
        if (CollectionUtil.isNotEmpty(hierInsList)) {
            List<Long> idList = hierInsList.stream().map(d -> d.getId()).collect(Collectors.toList());
            apiSendDataBatchSave(idList, className, model, ConstantInfo.OP_TYPE_ADD, true);
        }
    }

    /**
     * 3、计量单位
     */
    private void initConsumeSendInfo(String className) {
        String condition = " id not in (select sendValue from api_send_data where sendValue is not null and model ='consume' and className ='" + className + "')";
        List<ConsumeInstance> consumeInstances = this.consumeInstanceDslService.queryByClassName(className, condition);
        if (CollectionUtil.isNotEmpty(consumeInstances)) {
            List<Long> idList = consumeInstances.stream().map(d -> d.getId()).collect(Collectors.toList());
            apiSendDataBatchSave(idList, className, "consume", ConstantInfo.OP_TYPE_ADD, false);
        }
    }

    /**
     * 资源类数据发送初始化
     *
     * @param className 类名
     */
    private void initResourceSendInfo(String className) {
        String condition = " id not in (select sendValue from api_send_data where sendValue is not null and model ='resource' and className ='" + className + "')";
        List<ResourceInstance> resourceInstances = this.resourceInstanceDslService.queryByClassName(className, condition);
        if (CollectionUtil.isNotEmpty(resourceInstances)) {
            List<Long> idList = resourceInstances.stream().map(d -> d.getId()).collect(Collectors.toList());
            apiSendDataBatchSave(idList, className, "resource", ConstantInfo.OP_TYPE_ADD, false);
        }
    }

    /**
     * 4、供应商分类
     */
    private void initLogicSendInfo(String className,String condition) {
        condition += " and id not in (select sendValue from api_send_data where sendValue is not null and model ='logic' and className ='" + className + "')";
        List<LogicInstance> logicInstances = this.logicInstanceDslService.queryByClassName(className, false, condition);
        if (CollectionUtil.isNotEmpty(logicInstances)) {
            List<Long> idList = logicInstances.stream().map(d -> d.getId()).collect(Collectors.toList());
            apiSendDataBatchSave(idList, className, "logic", ConstantInfo.OP_TYPE_ADD, false);
        }
    }

    @Override
    public void apiSendDataBatchSave(List<Long> idList, String className, String model, String opType, Boolean hierFlag) {
        List<ApiSendData> apiSendDataList = new ArrayList<>();
        idList.forEach(id -> {
            JSONArray fieldValues = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ConstantInfo.FIELD_NAME, ConstantInfo.ID);
            jsonObject.put(ConstantInfo.FIELD_TYPE, ConstantInfo.TYPE_INTEGER);
            jsonObject.put(ConstantInfo.FIELD_VALUE, id);
            fieldValues.add(jsonObject);
            ApiSendData apiSendData = new ApiSendData();
            apiSendData.setClassName(className);
            apiSendData.setModel(model);
            apiSendData.setFieldValues(fieldValues);
            apiSendData.setOpType(opType);
            apiSendData.setHierFlag(hierFlag);
            apiSendData.setSendKey(ConstantInfo.ID);
            apiSendData.setSendValue(String.valueOf(id));
            apiSendDataList.add(apiSendData);
        });
        this.apiSendDataDslService.batchSave(apiSendDataList);
    }

    public void dealSendDataForInstance(JSONObject jsonObject, String model, String opType, Boolean hierFlag) {
        String className = jsonObject.getString(ConstantInfo.CLASS_NAME);
        boolean need = this.needTrans(className, model, opType);
        if (need) {
            Long id = jsonObject.getLong("id");
            List<Long> idList = Collections.singletonList(id);
            this.apiSendDataBatchSave(idList, className, model, opType, hierFlag);
        }
    }

    private void dealSendData(JSONObject sendData, JSONObject sendObj, String sourceName, int sourceType, String parentSourceName, int parentSourceType) {
        if(sendObj == null || sendObj.size() < 1){
            return;
        }

        //1、如果sourceName空值 并且parentSourceName也是空值，则直接添加到sendData的根节点上
        if (StringUtils.isBlank(sourceName) && StringUtils.isBlank(parentSourceName)) {
            sendData.putAll(sendObj);
            return;
        }
        //2、如果sourceName不是空值 parentSourceName是空值，则本级节点为sendData的第一个节点
        if (StringUtils.isNotBlank(sourceName) && StringUtils.isBlank(parentSourceName)) {
            this.dealSourceNotEmpty(sendData, sendObj, sourceName, sourceType);
            return;
        }
        
        //3、如果sourceName是空值 parentSourceName 不是空值，则本级节点为sendData的第一个节点
        if (StringUtils.isBlank(sourceName) && StringUtils.isNotBlank(parentSourceName)) {
            this.dealParentSourceNotEmpty(sendData, sendObj, parentSourceName, parentSourceType);
            return;
        }
        
        //4、如果sourceName不是空值 parentSourceName 不是空值，如果是jsonObject 测试添加上去，否作为数组加入
        this.dealSourceNotAllEmpty(sendData, sendObj, sourceName, sourceType, parentSourceName, parentSourceType);
    }

    private static void dealSourceNotEmpty(JSONObject sendData, JSONObject sendObj, String sourceName, int sourceType) {
        if (sourceType == 1) {
            sendData.put(sourceName, sendObj);
        } else {
            JSONArray tempArray = sendData.getJSONArray(sourceName);
            JSONObject tempObj;
            if(tempArray == null || tempArray.size() <1){
                tempObj = new JSONObject();
                tempArray = new JSONArray();
                tempArray.add(tempObj);
            }else{
                tempObj = (JSONObject) tempArray.get(0);
                tempObj.putAll(sendObj);
            }
            sendData.put(sourceName, tempArray);
        }
    }

    private static void dealParentSourceNotEmpty(JSONObject sendData, JSONObject sendObj, String parentSourceName, int parentSourceType) {
        Object parentNode = sendData.get(parentSourceName);
        if (parentSourceType == 1) {
            JSONObject tempObj = parentNode != null ? (JSONObject) parentNode : new JSONObject();
            tempObj.putAll(sendObj);
            sendData.put(parentSourceName, tempObj);
        } else {
            JSONArray tempArray = parentNode != null ? (JSONArray) parentNode : new JSONArray();
            JSONObject tempObj;
            if (tempArray.size() > 0) {
                tempObj = (JSONObject) tempArray.get(0);
            } else {
                tempObj = new JSONObject();
                tempArray.add(tempObj);
            }
            tempObj.putAll(sendObj);
            sendData.put(parentSourceName, tempArray);
        }
    }

    private void dealSourceNotAllEmpty(JSONObject sendData, JSONObject sendObj, String sourceName, int sourceType, String parentSourceName, int parentSourceType) {
        if (StringUtils.isNotBlank(sourceName) && StringUtils.isNotBlank(parentSourceName)) {
            Object parentNode = sendData.get(parentSourceName);
            if (parentSourceType == 1) {
                JSONObject tempObj = parentNode != null ? (JSONObject) parentNode : new JSONObject();
                tempObj.put(sourceName, sendObj);
                sendData.put(parentSourceName,tempObj);
            }else{
                JSONArray tempArray = parentNode != null ? (JSONArray) parentNode : new JSONArray();
                JSONObject tempObj;
                if (tempArray.size() > 0) {
                    tempObj = (JSONObject) tempArray.get(0);
                } else {
                    tempObj = new JSONObject();
                    tempArray.add(tempObj);
                }
                dealCurrentSourceSendObj(sendObj, sourceName, sourceType, tempObj);
                sendData.put(parentSourceName,tempArray);
            }
        }
    }

    /**
     * 处理当前数据源发送节点
     * @param sendObj 发送数据对象
     * @param sourceName 当前发送数据源名称
     * @param sourceType 当前发送数据源类型，1、JSONObject,2、JSONArray
     * @param tempObj 监时参数
     */
    private void dealCurrentSourceSendObj(JSONObject sendObj, String sourceName, int sourceType, JSONObject tempObj) {
        if(sourceType == 1){
            JSONObject obj = tempObj.getJSONObject(sourceName);
            if (obj == null) {
                tempObj.put(sourceName, sendObj);
            } else {
                obj.putAll(sendObj);
            }
        }else if(sourceType == 2){
            JSONArray objAry = tempObj.getJSONArray(sourceName);
            if (objAry == null || objAry.size() < 1) {
                objAry = new JSONArray();
                objAry.add(sendObj);
                tempObj.put(sourceName,objAry);
            } else {
                JSONObject o = (JSONObject)objAry.get(0);
                o.putAll(sendObj);
            }
        }
    }

    /**
     * 获取实例信息
     *
     * @param model     模型名称
     * @param className 模型类名
     * @param condition 查询条件
     * @return 返回查询结果
     */
    private JSONObject getInsValues(String model, String className, String condition) {
        JSONObject jsonObject;
        switch (model) {
            case "logic":
                jsonObject = this.logicInstanceDslService.queryWithoutHier(condition, className, null).stream().findFirst().orElse(null);
                break;
            case "consume":
                jsonObject = this.consumeInstanceDslService.query(condition, className, null).stream().findFirst().orElse(null);
                break;
            case "resource":
                jsonObject = this.resourceInstanceDslService.query(condition, className, null).stream().findFirst().orElse(null);
                break;
            case "tank":
                jsonObject = this.tankInstanceDslService.queryWithoutHier(condition, className, null).stream().findFirst().orElse(null);
                break;
            default:
                jsonObject = new JSONObject();
                break;
        }
        JSONObject values = new JSONObject();
        if (jsonObject.getJSONObject("values") != null) {
            values = jsonObject.getJSONObject("values");
            values.put("id", jsonObject.get("id"));
            values.put("hierFlag", false);
            values.put("createTime", jsonObject.get("createTime"));
        }
        return values;
    }

    /**
     * 构建引用查询条件
     *
     * @param configInfo     配置信息
     * @param sourceDataList 已经处理的数据集合
     * @param condition      查询条件
     * @return 返回新构建的查询条件
     */
    private String buildRefCondition(ConfigInfo configInfo, List<JSONObject> sourceDataList, String condition) {
        RefInfo ref = configInfo.getRef();
        if (ref == null) {
            return condition;
        }
        String refModel = ref.getModel();
        String refClassName = ref.getClassName();
        List<RefProp> refProps = ref.getRefProps();
        for (RefProp prop : refProps) {
            String refFieldName = prop.getRefFieldName();
            String refFieldType = prop.getRefFieldType();
            String fieldName = prop.getCurFieldName();
            JSONObject jsonObject = sourceDataList.stream().filter(json -> json.getString(ConstantInfo.MODEL).equalsIgnoreCase(refModel) && json.getString(ConstantInfo.CLASS_NAME).equalsIgnoreCase(refClassName)).findFirst().orElse(null);
            if (jsonObject != null) {
                String fieldValue = jsonObject.getString(refFieldName);
                condition = buildCondition(condition, fieldName, refFieldType, fieldValue);
            }
        }
        return condition;
    }

    /**
     * 构建查询条件
     *
     * @param condition  查询条件
     * @param fieldName  字段名
     * @param fieldType  字段类型
     * @param fieldValue 字段值
     * @return 返回查询条件
     */
    private String buildCondition(String condition, String fieldName, String fieldType, String fieldValue) {
        String tempCondition;
        switch (fieldType.toLowerCase()) {
            case "datetime":
            case "date":
            case "string":
                tempCondition = fieldName + " = '" + fieldValue + "'";
                break;
            case "boolean":
                boolean dataValue = Boolean.valueOf(fieldValue);
                if (dataValue) {
                    tempCondition = fieldName + " = 1 ";
                } else {
                    tempCondition = fieldName + " = 0 ";
                }
                break;
            default:
                tempCondition = fieldName + " = " + fieldValue;
                break;
        }

        if (StringUtils.isNotBlank(condition)) {
            condition += " and " + tempCondition;
        } else {
            condition = tempCondition;
        }
        return condition;
    }
}
